package com.shujia;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;

import java.util.ArrayList;

public class HiveUDTF extends GenericUDTF {
    // 指定输出的列名 及 类型
    @Override
    public StructObjectInspector initialize(StructObjectInspector argOIs) throws UDFArgumentException {
        ArrayList<String> filedNames = new ArrayList<String>();
        ArrayList<ObjectInspector> filedObj = new ArrayList<ObjectInspector>();
        filedNames.add("col1");
        filedObj.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        filedNames.add("col2");
        filedObj.add(PrimitiveObjectInspectorFactory.javaStringObjectInspector);
        return ObjectInspectorFactory.getStandardStructObjectInspector(filedNames, filedObj);
    }

    // UDTF的逻辑
    // add jar /usr/local/soft/jars/Hive-1.0.jar;
    // create temporary function myUDTF as 'com.shujia.HiveUDTF'
    // myUDTF("key1:value1,key2:value2,key3:value3")
    @Override
    public void process(Object[] args) throws HiveException {
        String s = args[0].toString();
        String[] split = s.split(",");
        for (String kv : split) {
            String[] split1 = kv.split(":");
//            String key = split1[0];
//            String value = split1[1];
//            ArrayList<String> arrayList = new ArrayList<>();
//            arrayList.add(key);
//            arrayList.add(value);
//            // 将数据输出
//            forward(arrayList);
            forward(split1);
        }
    }

    // UDTF函数调用完成后需要执行的代码
    @Override
    public void close() throws HiveException {

    }
}
